﻿import { Component, OnInit, Injector, Input, Output, EventEmitter } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
    OccurrenceTime,
    CostBookingServiceProxy,
    ExcelCostImportInput,
    ExcelCell
} from '@shared/service-proxies/service-proxies';
import * as moment from 'moment';
import * as _ from 'lodash';

@Component({
    selector: 'import-to-excel',
    templateUrl: './import-to-excel.component.html'
})
export class ImportToExcelComponent extends AppComponentBase implements OnInit {
    constructor(injector: Injector, private _costBookingService: CostBookingServiceProxy) {
        super(injector);
    }

    @Input() title = '';
    @Input() excelType;

    selectedDate = new Date();
    fileName: string;
    fileData: Object;
    sheetData = [];

    ngOnInit(): void {
        this.fileName = '';
        this.fileData = new Object();
        this.sheetData = [];
    }

    onUpload(event) {
        this.fileName = event.fileName;

        this.fileData = event;
    }

    onSheetChange(event) {
        this.sheetData = event.sheetData;
    }

    confirmImport() {
        if (!this.sheetData || !this.sheetData.length) {
            this.message.warn('当前 Sheet 页没有数据');
            return;
        }
        this.message.confirm('确认导入当前数据吗？', this.l('AreYouSure'), isConfirmed => {
            if (isConfirmed) {
                this.primengTableHelper.showLoadingIndicator();

                let excelId = 'excel_' + moment().format('YYYYMMDDhhmmss');

                let cells = this.sheetData.map(el => {
                    let cell = new ExcelCell();
                    cell.cell = el.cell;
                    cell.value = el.value;

                    return cell;
                });

                let batches = _.chunk(cells, 100000);

                for (let index = 0; index < batches.length; index++) {
                    const value = batches[index];
                    let input = new ExcelCostImportInput();

                    input.id = excelId;

                    input.batchNum = index + 1;

                    input.totalNum = cells.length;

                    input.time = new OccurrenceTime();
                    input.time.month = this.selectedDate.getMonth() + 1;
                    input.time.year = this.selectedDate.getFullYear();

                    input.excelTitle = this.fileName;

                    input.excelType = this.excelType;

                    input.cells = value;

                    this._costBookingService.setExcelBatchDataToCache(input).subscribe(result => {});
                }

                this.primengTableHelper.hideLoadingIndicator();
                this.notify.success('数据上传成功，后台导入中');
            }
        });
    }
}
